package com.dream.oproject.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dream.oproject.base.web.BaseController;
import com.dream.oproject.web.models.User;

@Controller
@RequestMapping("/user/*")
public class UserController extends BaseController{

	@RequestMapping("default")
    public String index(ModelMap model) {  
		
        return "/user/user_default";  

	}
	
	// 用户资料测试数据
	private static List<User> users = new ArrayList<User>();
	static{
		for(int i=1; i<10; i++){
			User user = new User();
			user.id = i;
			user.name = "name" + i;
			user.phone = "phone" + i;
			user.addr = "addr" + i;
			user.duty = "duty" + i;
			
			users.add(user);
		}
	}
	
	@RequestMapping("userList")
    public @ResponseBody Map<String,Object> listUser(ModelMap model) {  
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("total", users.size());
		result.put("rows", users);
		return result; 
	}
	
	@RequestMapping("getUser")
	public @ResponseBody Map<String,Object> getUser(Integer id) throws Exception{
		User user = users.get(id-1);
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("user", user);
		return result;
	}
	
	@RequestMapping("save")
	public @ResponseBody Map<String,Object> save(User user,HttpServletResponse response) throws Exception{
		Map<String,Object> result = new HashMap<String,Object>();
		if (user.name.length() == 0){
			result.put("failure", true);
			result.put("msg", "用户名称必须填写。");
		} else {
			result.put("success", true);
			user.id = users.size()+1;
			users.add(user);
		}
		return result;
	}
	
	@RequestMapping("update")
	public @ResponseBody Map<String,Object> update(Integer id) throws Exception{
		Map<String,Object> result = new HashMap<String,Object>();
		User user = users.get(id-1).clone();
		if (user.name.length() == 0){
			result.put("failure", true);
			result.put("msg", "用户名称必须填写。");
		} else {
			result.put("success", true);
			user.id = id;
			users.set(id-1, user);
		}
		return result;
	}
}
